/**
* COPYRIGHT. whx. ALL RIGHTS RESERVED.
* Project: just-core
* Author: whx <harrywu304@gmail.com>
* Create On: Apr 11, 2012 8:13:49 PM
*/

package org.justframework.api.dispatcher;

import org.justframework.api.connector.Request;
import org.justframework.api.connector.Response;
import org.justframework.core.mapper.MapperFactory;
import org.justframework.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Basic Dispatcher
 */
public abstract class BaseDispatcher implements Dispatcher {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(BaseDispatcher.class);

	/* (non-Javadoc)
	 * @see org.justframework.api.dispatcher.Dispatcher#handle(org.justframework.api.connector.Request, org.justframework.api.connector.Response, org.justframework.server.RequestContext)
	 */
	@Override
	public void dispatch(Request request, Response response,
			RequestContext context) {
		logger.debug("requestObject [{}]", request);
		//response set referred requestId and requestTimestamp
		response.setRequestId(request.getRequestId());
		response.setRequestTimestamp(request.getRequestTimestamp());
		//response stamps request receive timestamp
		response.setReceiveTimestamp(System.currentTimeMillis());
		
		//do real dispatch action
		try{
			doDispatch(request,response,context);
		} catch(Exception e){
			logger.error("request dispatch throw exception",e);
			response.setErrorCode(-1);
			response.setContent(MapperFactory.getDefaultMapper().toSerial(e));
		}
		
		//response stamp reply timestamp
		response.setReplyTimestamp(System.currentTimeMillis());
		logger.debug("responseObject [{}]", response);
	}
	
	public abstract void doDispatch(Request request, Response response,
			RequestContext context) throws Exception;

}
